package com.tuanbiao.ui.project;

import android.content.Context;
import android.content.Intent;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.abiao.lib_utils.SPUtils;
import com.abiao.lib_utils.ViewUtils;
import com.codekidlabs.storagechooser.StorageChooser;
import com.hzjq.data.entity.PmEntity;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.ProjectController;
import com.tuanbiao.databinding.ActivityProjectManagerBinding;
import com.tuanbiao.dialog.MessageDialog;
import com.tuanbiao.events.ProjectManageEvent;
import com.tuanbiao.models.ProjectModel;
import com.tuanbiao.presenter.ProjectManagerPresenter;
import com.tuanbiao.utils.BLEUtils;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.LibCollections;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;


/**
 * @author abiao
 * @since 2022/3/25 11:47
 */
public class ProjectManageActivity extends BasePresenterActivity<ProjectManagerPresenter, ActivityProjectManagerBinding> implements ProjectController.View {
    private ProjectManageAdapter projectManageAdapter;
    private final ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , this::onAddProjectResult);

    private void onAddProjectResult(ActivityResult result) {
        if (result.getResultCode() == RESULT_OK) {
            mPresenter.refresh();
        }
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, ProjectManageActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected ProjectManagerPresenter createPresenter() {
        return new ProjectManagerPresenter(new ProjectModel(), this);
    }

    @Override
    protected ActivityProjectManagerBinding getBindingView() {
        return ActivityProjectManagerBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.ivAdd.setOnClickListener(view -> {
            activityResultLauncher.launch(ProjectAddActivity.createIntent(getActivity()));
        });
        binding.btnImport.setOnClickListener(v -> {
            showFileChooser();
        });
        projectManageAdapter = new ProjectManageAdapter();
        projectManageAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            PmEntity entity = (PmEntity) adapter.getItem(position);
            entity.setSelect(!entity.isSelect());
            mPresenter.updateProject(entity);
        });
        projectManageAdapter.addChildClickViewIds(R.id.iv_check, R.id.iv_edit);
        projectManageAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            PmEntity entity = (PmEntity) adapter.getItem(position);
            if (null != entity) {
                switch (view.getId()) {
                    case R.id.iv_check:
                        entity.setSelect(!entity.isSelect());
                        mPresenter.updateProject(entity);
                        break;
                    case R.id.iv_edit:
                        EventBus.getDefault().postSticky(new ProjectManageEvent(entity));
                        activityResultLauncher.launch(ProjectAddActivity.createIntent(getActivity()));
                        break;
                    default:
                        break;
                }
            }
        });
        projectManageAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            PmEntity entity = (PmEntity) adapter.getItem(position);
            showDeleteDialog(entity);
            return false;
        });
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvContent.setAdapter(projectManageAdapter);
        binding.srlContent.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                mPresenter.loadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.refresh();
            }
        });
        binding.srlContent.autoRefresh();
    }

    private void showDeleteDialog(PmEntity entity) {
        new MessageDialog.Builder(getActivity())
                .setTitle("提示")
                .setMessage("确定删除当前项目?")
                .setListener(dialog -> mPresenter.deleteProject(entity)).show();
    }

    @Override
    protected void initData() {
        mPresenter.refresh();
    }

    @Override
    public void setProjects(List<PmEntity> entities) {
        binding.srlContent.finishRefresh();
        if (LibCollections.isEmpty(entities)) {
            projectManageAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        }
        projectManageAdapter.setNewInstance(entities);
    }

    @Override
    public void addProjects(List<PmEntity> entities) {
        binding.srlContent.finishLoadMore();
        if (LibCollections.isEmpty(entities)) binding.srlContent.finishLoadMoreWithNoMoreData();
        else projectManageAdapter.addData(entities);
    }

    private void showFileChooser() {
        // Initialize Builder
        ArrayList<String> formats = new ArrayList<>();
//        formats.add(".txt");
        StorageChooser chooser = new StorageChooser.Builder()
                .withActivity(getActivity())
                .withFragmentManager(getFragmentManager())
                .withMemoryBar(true)
//                .customFilter(formats)
                .allowCustomPath(true)
                .actionSave(false)
                .withPreference(SPUtils.getInstance().getSp())
                .skipOverview(true, BLEUtils.getDir())
                .setType(StorageChooser.FILE_PICKER)
                .build();

// Show dialog whenever you want by
        chooser.show();

// get path that the user has chosen
        chooser.setOnSelectListener(new StorageChooser.OnSelectListener() {
            @Override
            public void onSelect(String path) {
                Timber.e("SELECTED_PATH:" + path);
                mPresenter.importProject(path);
            }
        });
    }
}
